package com.example.fx.login

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.example.base.entity.LoginEntityResult
import com.example.base.entity.SendCodeEntityResult
import com.example.base.mvvm.BaseViewModel
import com.google.gson.Gson
import kotlinx.coroutines.launch
import okhttp3.MediaType
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.RequestBody

class LoginViewModel:BaseViewModel() {

    val sendCodeSuccess  = MutableLiveData<SendCodeEntityResult>()
    val sendCodeFail = MutableLiveData<String>()
    //发送验证码
    fun sendCode(phone:String){
        viewModelScope.launch {
            try {
                sendCodeSuccess.value = apiService.sendCode(phone)
            }catch (e:Exception){
                sendCodeFail.value = e.message
            }
        }
    }

    val loginSuccess = MutableLiveData<LoginEntityResult>()
    val loginFail = MutableLiveData<String>()
    //实现验证码登录
    fun login(phone:String,code:String){
        viewModelScope.launch {
            try {
                val map = mutableMapOf<String,String>()
                map.put("phone",phone)
                map.put("captcha",code)
                map.put("spread_spid","0")
                val json = Gson().toJson(map)
                val body = RequestBody.create("application/json;charset=utf-8".toMediaType(),json)
                loginSuccess.value = apiService.login(body)
            }catch (e:Exception){
                loginFail.value = e.message
            }
        }
    }
}